package de.wittekind.bundesjugendspiele.server.calc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.wittekind.bundesjugendspiele.server.interfaces.Discipline;
import de.wittekind.bundesjugendspiele.server.interfaces.Schueler.Gender;
import de.wittekind.bundesjugendspiele.server.interfaces.Try;

public class PointCalculator {

	public static int getPoints(Try[] tries, Gender gen) throws IOException {
		Map<Discipline, List<Try>> disciplines = new HashMap<Discipline, List<Try>>();
		int points = 0;
		for (Try tr : tries) {
			Discipline dis = tr.getDiscipline();
			if (!disciplines.containsKey(dis)) {
				List<Try> list = new ArrayList<Try>();
				disciplines.put(dis, list);
			}
			disciplines.get(dis).add(tr);
		}
		for (Discipline dis : disciplines.keySet()) {
			points += analyseList(disciplines.get(dis), gen);
		}
		return points;
	}

	private static int analyseList(List<Try> list, Gender gen)
			throws IOException {
		int highest = 0;
		for (Try tr : list) {
			int points = calcTry(tr, gen);
			if (points > highest) {
				highest = points;
			}
		}
		return highest;
	}

	private static int calcTry(Try tr, Gender gen) throws IOException {
		Discipline dis = tr.getDiscipline();
		Map<Integer, Double> map = Formula.get(gen, dis);
		int points=0;

		double m = tr.getValue();
		double a = map.get(Formula.A);
		double c = map.get(Formula.C);
		double d = map.get(Formula.D);
		if(m!=0)
		{
		if (Discipline.AUSDAUER.hasDiscipline(dis)
				|| Discipline.SPRINT.hasDiscipline(dis)) {
			double zuschlag = 0;
			if (Discipline.SPRINT.hasDiscipline(dis))
				zuschlag = 0.24;
			points = new Double((d / (m + zuschlag) - a) / c).intValue();
		} else {
			points = new Double((Math.sqrt(m) - a) / c).intValue();
		}
		}
		//DEBUG
		System.out.println("Geschlecht:"+gen);
		System.out.println("Disziplin:"+ tr.getDiscipline());
		System.out.println("Versuchswert:" + tr.getValue() + tr.getUnit());
		System.out.println("Punkte:"+points);

		return points;
	}

}
